package com.yunliuchain.examination.common.exception;

import com.yunliuchain.examination.common.res.ApiResult;
import com.yunliuchain.examination.common.res.ApiResult;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 异常处理类
 */
@Component
public class MyExceptionHandler  implements HandlerExceptionResolver {


    @Override
    public  ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {
        response.setContentType("json/application; charset=UTF-8");
        OutputStream writer = null;
        try {
            writer = response.getOutputStream();
            ApiResult apiResult = ApiResult.fail("操作失败: "+ex.getMessage());
            writer.write(apiResult.toString().getBytes("utf-8"));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
